﻿using System.Linq;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using DotNetNuke.Common.Utilities;
using DotNetNuke.Services.Localization;
using System.Globalization;
using Telerik.Web.UI;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Services.Personalization;

namespace DotNetNuke.Web.UI.WebControls
{

    public class DnnLanguageComboBox : WebControl
    {

        #region "Private Members"

        private bool _AutoPostBack = Null.NullBoolean;
        private string _FlagImageUrlFormatString = "~/images/Flags/{0}.gif";
        private Dictionary<string, Locale> _HideLanguagesList = new Dictionary<string, Locale>();
        private bool _IncludeNoneSpecified = false;
        private LanguagesListType _LanguagesListType = LanguagesListType.Enabled;
        private int _PortalId;
        private bool _ShowFlag = true;
        private bool _ShowModeButtons = true;

        private string _ViewTypePersonalizationKey;
        private RadioButtonList _ModeRadioButtonList;
        private DnnComboBox _NativeCombo;

        private DnnComboBox _EnglishCombo;

        private string _OriginalValue;


        #endregion

        #region "Public Events"

        public event EventHandler ItemChanged;
        public event EventHandler ModeChanged;

        #endregion

        #region "Constructor"
        public DnnLanguageComboBox()
        {
            _ViewTypePersonalizationKey = "ViewType" + PortalId.ToString();
        }
        #endregion

        #region "Public Properties"

        private string DisplayMode
        {
            get
            {
                string _DisplayMode = Convert.ToString(Personalization.GetProfile("LanguageDisplayMode", _ViewTypePersonalizationKey));
                if (string.IsNullOrEmpty(_DisplayMode))
                    _DisplayMode = "NATIVE";
                return _DisplayMode;
            }
        }

        public string FlagImageUrlFormatString
        {
            get { return _FlagImageUrlFormatString; }
            set { _FlagImageUrlFormatString = value; }
        }

        public Dictionary<string, Locale> HideLanguagesList
        {
            get { return _HideLanguagesList; }
            set { _HideLanguagesList = value; }
        }

        public bool IncludeNoneSpecified
        {
            get { return _IncludeNoneSpecified; }
            set { _IncludeNoneSpecified = value; }
        }

        public LanguagesListType LanguagesListType
        {
            get { return _LanguagesListType; }
            set { _LanguagesListType = value; }
        }

        public int PortalId
        {
            get { return _PortalId; }
            set { _PortalId = value; }
        }

        public string SelectedValue
        {
            get
            {
                string _SelectedValue = DisplayMode.ToUpperInvariant() == "NATIVE" ? _NativeCombo.SelectedValue : _EnglishCombo.SelectedValue;
                if (_SelectedValue == "None")
                {
                    _SelectedValue = Null.NullString;
                }
                return _SelectedValue;
            }
        }

        public bool ShowFlag
        {
            get { return _ShowFlag; }
            set { _ShowFlag = value; }
        }

        public bool ShowModeButtons
        {
            get { return _ShowModeButtons; }
            set { _ShowModeButtons = value; }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Determines whether the List Auto Posts Back
        /// </summary>
        /// -----------------------------------------------------------------------------
        public bool AutoPostBack
        {
            get { return _AutoPostBack; }
            set { _AutoPostBack = value; }
        }

        #endregion

        #region "Private Methods"

        private void DataBind(bool refresh)
        {
            if (refresh)
            {
                List<CultureInfo> cultures = null;
                switch (LanguagesListType)
                {
                    case LanguagesListType.Supported:
                        cultures = LocaleController.Instance.GetCultures(LocaleController.Instance.GetLocales(Null.NullInteger));
                        break;
                    case LanguagesListType.Enabled:
                        cultures = LocaleController.Instance.GetCultures(LocaleController.Instance.GetLocales(PortalId));
                        break;
                    default:
                        cultures = new List<CultureInfo>(CultureInfo.GetCultures(CultureTypes.SpecificCultures));
                        break;
                }

                foreach (KeyValuePair<string, Locale> lang in HideLanguagesList)
                {
                    string cultureCode = lang.Value.Code;
                    CultureInfo culture = cultures.Where(c => c.Name == cultureCode).SingleOrDefault();
                    if (culture != null)
                    {
                        cultures.Remove(culture);
                    }
                }

                _NativeCombo.DataSource = cultures.OrderBy(c => c.NativeName);
                _EnglishCombo.DataSource = cultures.OrderBy(c => c.EnglishName);
            }


            _NativeCombo.DataBind();
            _EnglishCombo.DataBind();

            if (IncludeNoneSpecified && refresh)
            {
                _EnglishCombo.Items.Insert(0, new RadComboBoxItem(Localization.GetString("System_Default", Localization.SharedResourceFile), "None"));
                _NativeCombo.Items.Insert(0, new RadComboBoxItem(Localization.GetString("System_Default", Localization.SharedResourceFile), "None"));
            }
        }

        #endregion

        #region "Protected Methods"

        protected override void OnInit(System.EventArgs e)
        {
            base.OnInit(e);
            _NativeCombo = new DnnComboBox();
            _NativeCombo.DataValueField = "Name";
            _NativeCombo.DataTextField = "NativeName";
            _NativeCombo.SelectedIndexChanged += Item_Changed;
            Controls.Add(_NativeCombo);

            _EnglishCombo = new DnnComboBox();
            _EnglishCombo.DataValueField = "Name";
            _EnglishCombo.DataTextField = "EnglishName";
            _EnglishCombo.SelectedIndexChanged += Item_Changed;
            Controls.Add(_EnglishCombo);

            _ModeRadioButtonList = new RadioButtonList();
            _ModeRadioButtonList.AutoPostBack = true;
            _ModeRadioButtonList.RepeatDirection = RepeatDirection.Horizontal;
            _ModeRadioButtonList.Items.Add(new ListItem(Localization.GetString("NativeName", Localization.GlobalResourceFile), "NATIVE"));
            _ModeRadioButtonList.Items.Add(new ListItem(Localization.GetString("EnglishName", Localization.GlobalResourceFile), "ENGLISH"));
            _ModeRadioButtonList.SelectedIndexChanged += Mode_Changed;
            Controls.Add(_ModeRadioButtonList);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            _OriginalValue = SelectedValue;
        }

        protected virtual void OnItemChanged()
        {
            if (ItemChanged != null)
            {
                ItemChanged(this, new EventArgs());
            }
        }

        protected void OnModeChanged(EventArgs e)
        {
            if (ModeChanged != null)
            {
                ModeChanged(this, e);
            }
        }


        protected override void OnPreRender(System.EventArgs e)
        {
            if (DisplayMode.ToUpperInvariant() == "ENGLISH")
            {
                if (_EnglishCombo.Items.FindItemByValue(_OriginalValue) != null)
                {
                    _EnglishCombo.Items.FindItemByValue(_OriginalValue).Selected = true;
                }
            }
            else
            {
                if (_NativeCombo.Items.FindItemByValue(_OriginalValue) != null)
                {
                    _NativeCombo.Items.FindItemByValue(_OriginalValue).Selected = true;
                }
            }

            _ModeRadioButtonList.Items.FindByValue(DisplayMode).Selected = true;

            foreach (RadComboBoxItem item in _EnglishCombo.Items)
            {
                item.ImageUrl = string.Format(FlagImageUrlFormatString, item.Value);
            }
            foreach (RadComboBoxItem item in _NativeCombo.Items)
            {
                item.ImageUrl = string.Format(FlagImageUrlFormatString, item.Value);
            }

            _EnglishCombo.AutoPostBack = AutoPostBack;
            _EnglishCombo.Visible = (DisplayMode.ToUpperInvariant() == "ENGLISH");

            _NativeCombo.AutoPostBack = AutoPostBack;
            _NativeCombo.Visible = (DisplayMode.ToUpperInvariant() == "NATIVE");

            _ModeRadioButtonList.Visible = ShowModeButtons;

            _EnglishCombo.Width = Width;
            _NativeCombo.Width = Width;

            base.OnPreRender(e);
        }

        #endregion

        #region "Public Methods"

        public void SetLanguage(string code)
        {
            if (string.IsNullOrEmpty(code))
            {
                _NativeCombo.SelectedIndex = _NativeCombo.FindItemIndexByValue("None");
                _EnglishCombo.SelectedIndex = _EnglishCombo.FindItemIndexByValue("None");
            }
            else
            {
                _NativeCombo.SelectedIndex = _NativeCombo.FindItemIndexByValue(code);
                _EnglishCombo.SelectedIndex = _EnglishCombo.FindItemIndexByValue(code);
            }
        }

        public override void DataBind()
        {
            DataBind(!Page.IsPostBack);
        }

        #endregion

        #region "Event Handlers"

        private void Mode_Changed(object sender, EventArgs e)
        {
            Personalization.SetProfile("LanguageDisplayMode", _ViewTypePersonalizationKey, _ModeRadioButtonList.SelectedValue);

            //Resort
            DataBind(true);

            OnModeChanged(EventArgs.Empty);
        }

        private void Item_Changed(object sender, EventArgs e)
        {
            OnItemChanged();
        }

        #endregion


    }

}
